﻿using System;
using System.Configuration;
using System.Linq;
using Talentnet.Core.Utilities;
using Talentnet.Core.Utilities.Cryptophy;
using Talentnet.Core.Utilities.Mail;
using Talentnet.Data.Access;
using Talentnet.Core.Web;
using System.Web;

[PagePermission("ManUsr")]
public partial class admin_UpdateUser : NormalPage
{
    SEC_User user = new SEC_User();
    string loginName
    {
        get
        {
            if (ViewState["LoginName"] != null)
                return ViewState["LoginName"].ToString();
            return string.Empty;
        }
        set
        {
            ViewState["LoginName"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = LoadText("ManageUser", "TitleCreateUser");
        PageType = SecurePageType.Modal;
        if (!IsPostBack && IsSecureQueryString)
        {
            Page.Title = LoadText("ManageUser", "TitleEditUser");
            loginName = SecureQueryString["u"];
            BindUserInfo();
        }
        //Load label
        lblUserName.Text = LoadText("ManageUser", lblUserName.ID);
        lblFirstName.Text = LoadText("ManageUser", lblFirstName.ID);
        lblLastName.Text = LoadText("ManageUser", lblLastName.ID);
        lblEmail.Text = LoadText("ManageUser", lblEmail.ID);
    }

    private void BindUserInfo()
    {
        user = this.DBUser.GetUser(SessionManager.CurrentUser.ClientID, loginName);
        txtUserName.Text = user.LoginName;
        txtFirstName.Text = user.UserNameFirst;
        txtLastName.Text = user.UserNameLast;
        txtEmail.Text = user.Email;
        txtUserName.Enabled = false;
    }

    protected void btnUpdateUser_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(loginName))//Create new
        {
            //Step0: Check duplicate loginname
            SEC_User userExisted = this.DBUser.GetUser(SessionManager.CurrentUser.ClientID, txtUserName.Text.Trim());
            if (userExisted != null)
            {
                ltrMessage.Text = LoadText("ManageUser", "DuplicateUser");
                return;
            }

            //Step1: Create User
            Guid userId = Guid.NewGuid();
            user.RecId = userId;
            user.ClientID = SessionManager.CurrentUser.ClientID;
            user.LoginName = txtUserName.Text.Trim();
            user.UserNameFirst = txtFirstName.Text.Trim();
            user.UserNameLast = txtLastName.Text.Trim();
            string tempPwd = CryptoAgent.Current.MD5(userId.ToString());
            user.UserPassword = tempPwd;
            user.UserPasswordType = (int)SiteEnums.PasswordType.SysPwd;
            user.UserPasswordDTS = DateTime.Now;
            user.Status = (byte)SiteEnums.UserStatus.WaitForActive;
            user.Email = txtEmail.Text.Trim();
            user.ThemeId = SiteConstants.Talentnet.THEME_ID;
            user.CreatedBy = SessionManager.CurrentUser.RecId;
            user.CreatedDTS = DateTime.Now;

            this.DBUser.CreateNewUser(user);

            //Step2: Assign Role for User
            SEC_UsersInRole userInRole = new SEC_UsersInRole();
            userInRole.RoleId = (int)SiteEnums.UserType.Consultants;
            userInRole.UserRecId = userId;
            userInRole.CreatedDTS = DateTime.Now;
            this.DBUser.AssignRoleForUser(userInRole);

            //Step3: Send Email
            string fromEmail = SessionManager.MailSetting.EmailContact;
            //Load mail template
            System.IO.StreamReader mailTemplate = new System.IO.StreamReader(MapPath(@"~\App_Data\EmailTemplates\ActiveAccount.htm"));
            string mail_body = mailTemplate.ReadToEnd();
            string subject = "[Talentnet] - Kich Hoat Tai Khoan";
            mailTemplate.Close();
            mail_body = mail_body.Replace("[username]", txtUserName.Text.Trim());
            string link = Request.Url.AbsoluteUri.Replace(@"admin/UpdateUser.aspx", @"freeaccess/ActiveAccount.aspx?") + BuildStaticQueryString("k=" + tempPwd);
            mail_body = mail_body.Replace("[link]", link);
            MailServices.SendEmail(fromEmail, txtEmail.Text.Trim(), subject, mail_body, SessionManager.MailSetting);
        }
        else//Edit
        {
            user = this.DBUser.GetUser(SessionManager.CurrentUser.ClientID, loginName);
            if (user != null)
            {
                user.LoginName = loginName;
                user.UserNameFirst = txtFirstName.Text;
                user.UserNameLast = txtLastName.Text;
                user.Email = txtEmail.Text;
                this.DBUser.UpdateUser(user);
            }
        }

        ClientScript.RegisterStartupScript(GetType(), "ReloadUserList", "<script>parent.RebindUserList();CloseModalWindow();</script>");
    }
}
